# -*- coding: utf-8 -*
# Create your views here.
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import get_object_or_404,render_to_response,render
from django.template import RequestContext
from django.db.models import Q, F, Sum
from mysitebbs.form import *
from mysitebbs.models import *
from django.contrib.auth.decorators import login_required

#get_object_or_404

def home(request):
	#return render_to_response("bbs/index.html",context_instance=RequestContext(request))
	ctx = {}
	ctx['postlist'] = PostModel.objects.filter(first=1).order_by('-dateline')[:20]
	
	return render_to_response("bbs/index.html",ctx,context_instance=RequestContext(request))

#浏览帖子
def viewPosts(request,forumid="0",threadid="0"):
	ctx = {}
	ctx['postlist'] = PostModel.objects.filter(pk=threadid).order_by('position')[:20]
	ctx['threaddata'] = TopicModel.objects.get(pk=threadid)
	return render_to_response("bbs/viewPost.html",ctx,context_instance=RequestContext(request));
	
#主题列表
def viewTopics(request,forum_id="0"):
	ctx = {}
	ctx['topiclist'] = TopicModel.objects.filter(forum=forum_id).order_by('-dateline')[:20]
	#ctx['forumdata'] = ForumModel.objects.get(fid=int(forumid))
	return render_to_response("bbs/viewThreads.html",ctx,context_instance=RequestContext(request));

#栏目列表
def viewForums(request):
	fms = {}
	fms['forumlist'] = ForumModel.objects.filter(status=1)
	return render_to_response("bbs/index.html",fms,context_instance=RequestContext(request));


@login_required
def quickpost(request,threadid="0",forumid="0"):
	if request.method == 'POST':
		form = PostForm(request.POST)
		#return HttpResponse(time.time())
		if form.is_valid():
			pm = PostModel(
				topic = int(threadid),
				subject = form['subject'].value(),
				message = form['message'].value(),
				authorip = request.META['REMOTE_ADDR'],
				authorid = request.user.id,
				author = request.user.username,
				)
				
			if threadid == "0":
				pm.first = 1
				
				tmobj = {'fid':forumid,
					'author':pm.author,
					'authorid':pm.authorid,
					'subject': pm.subject,
					'lastposter':pm.author,}					
				tf = ThreadForm(tmobj)
				
				if tf.is_valid():
					tf.save()
				
					pm.tid = tf.tid				
					pm.save()
				else:
					return HttpResponseRedirect("/bbs/")
			else:
				tm = TopicModel.objects.get(tid=int(threadid))
				tm.lastpost = pm.author
				tm.replies += 1
				
				pm.position = tm.replies
				
				pm.save()
				tm.save()
				
			return HttpResponseRedirect("/bbs/")
		else:
			return render_to_response("test.html",{'form':form});
			#return HttpResponse(request.POST['subject']);
	else:
		return HttpResponse("request.method")
	return HttpResponse("quickpost")


@login_required
def add_post(request,forum_id,topic_id):
	#if not request.method == "POST":
		#if forum_id:
			#return show_forum(request,forum_id)
		#elif topic_id:
			#return show_topic(request,topic_id)
		#else:
			#return HttpResponse("404")

	forum = None
	topic = None
	posts = None

	if forum_id:
		forum = get_object_or_404(ForumModel,pk=forum_id)
	elif topic_id:
		topic = get_object_or_404(TopicModel,pk=topic_id)
		#报错 
		#posts = topic.posts.all().select_related()
		posts = topic.posts
	
	ip = request.META.get('REMOTE_ADDR',None)
	
	form = NewPostForm(request.POST,forum=forum,topic=topic,user=request.user,ip=ip)
	if form.is_valid():
		#return HttpResponse(form.cleaned_data['subject'])
		form.save()
		return HttpResponse(request.path)
		if forum_id:
			return show_forum(request,forum_id)
		else:
			#TopicModel.objects.filter(pk=topic.id).update(replies=F('replies') + 1)
			return show_topic(request,topic_id)
	else:
		return render_to_response("test.html",{'form':form});
		
def show_forum(request,forum_id):
	forum = ForumModel.objects.get(pk=forum_id)
	
	topics = forum.topics.order_by('-lastpost_time').select_related()
	
	to_return = {'topiclist':topics,
				'forumdata':forum
				}
	return render_to_response("bbs/show_forum.html",to_return,context_instance=RequestContext(request));
	
def show_topic(request,topic_id):
	topic = TopicModel.objects.get(pk=int(topic_id))
	TopicModel.objects.filter(pk=topic.id).update(views=F('views') + 1)
	#报错 
	#postlist = topic.posts.order_by('-dateline').select_related()  
	
	#forum = topic.
	
	postlist = PostModel.objects.filter(topic=topic_id)
	to_return = {'topicdata':topic,
				'postlist':postlist,
				}
	return render_to_response("bbs/show_topic.html",to_return,context_instance=RequestContext(request));






